package security;

import java.io.IOException;
import java.io.Serializable;
import javax.crypto.Cipher;
import javax.crypto.SealedObject;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.GeneralSecurityException;

/**
 * This class implements the abstract class SealedObj using the AES algorithm
 */
public class SealedObjAES extends SealedObj{

	
    /**
     * The size of the key
     */
    public static final int keySize = 16;

    /**
     *  Cipher object  for encryption and decryption
     */
	private Cipher cipher;

    /**
     * SecretKeySpec object specifies a secret key in a provider-independent fashion
     */
	private SecretKeySpec keySpec;


    /**
     * Class constructor specifying key
     * 
     * @param keyBytes key
     * @throws java.security.InvalidKeyException If an exception for invalid Keys (invalid encoding, wrong length, uninitialized, etc)  error occurs
     * @throws java.security.GeneralSecurityException If an generic security exception error occurs
     */
    public SealedObjAES(byte[] keyBytes)
            throws InvalidKeyException, GeneralSecurityException {
		
		if(keyBytes.length!=keySize)
			throw new InvalidKeyException();
		
		cipher = Cipher.getInstance("AES");
		keySpec = new SecretKeySpec(keyBytes,"AES");
	}


	protected SealedObject closedObj(Object obj)
            throws IOException, GeneralSecurityException{

		cipher.init(Cipher.ENCRYPT_MODE, keySpec);

		return new SealedObject((Serializable)obj,cipher);
	}


	protected Object unclosedObj(SealedObject sealedObj)
            throws  IOException, ClassNotFoundException,
	GeneralSecurityException{

		cipher.init(Cipher.DECRYPT_MODE, keySpec);

		return sealedObj.getObject(cipher);
	}


}